using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Rotempco.Core.Logic
{
    public class StringLogic
    {
        public static bool TrimAndValidateEmpty(ref string input)
        {
            input = input.Trim();

            if (string.IsNullOrEmpty(input))
                return false;

            return true;
        }

        public static string ReplaceString(string str, string oldValue, string newValue, StringComparison comparison)
        {
            StringBuilder sb = new StringBuilder();
            int previousIndex = 0;
            int index = str.IndexOf(oldValue, comparison);
            while (index != -1)
            {
                sb.Append(str.Substring(previousIndex, index - previousIndex));
                sb.Append(newValue);
                index += oldValue.Length;
                previousIndex = index;
                index = str.IndexOf(oldValue, index, comparison);
            }
            sb.Append(str.Substring(previousIndex));
            return sb.ToString();
        }

        public static string TextToHtml(string text)
        {
            return text.Replace("\r\n", "<br>");
        }

        public static string ReplaceFirstInstance(string str, string oldValue, string newValue, StringComparison comparison = StringComparison.InvariantCulture)
        {
            int pos = str.IndexOf(oldValue, comparison);
            if (pos < 0)
                return str;

            return str.Substring(0, pos) + newValue + str.Substring(pos + oldValue.Length);
        }

        public static string ReplaceLastInstance(string str, string oldValue, string newValue, StringComparison comparison = StringComparison.InvariantCulture)
        {
            int pos = str.LastIndexOf(oldValue, comparison);
            if (pos < 0)
                return str;

            return str.Substring(0, pos) + newValue + str.Substring(pos + oldValue.Length);
        }

        public static string ByteArrayToString(byte[] byteArray)
        {
            UTF7Encoding encoding = new UTF7Encoding();
            return encoding.GetString(byteArray);
        }

        public static byte[] StringToByteArray(string str)
        {
            UTF7Encoding encoding = new UTF7Encoding();
            return encoding.GetBytes(str);

        }
    }
}
